Day 5 - Semicolon, logical AND, pipes

All right. Let’s just think this thing through logically.

Back to the Future Part III (1990)

So far it looks like bash and Unix are not using those nasty strange symbols many other programming

languages or systems use. Well, that’s good, isn’t it? Yes, but it’s also tragically untrue. In this lesson

we will meet some of the fancy hieroglyphs that Unix uses to express complex behaviour, so if you

are still ruminating on that class of ancient Babylonian language that you missed at the university,

be happy. You will soon catch up.

First of all let’s explore the semicolon. Try to add a semicolon between two commands, like for

example

$ echo "First string"; echo "Second string"

As you can see bash runs both in sequence, so ; clearly stands for a sort of “and” between two

commands. It is interesting to see what happens if one of the commands fails, though. Let’s try to

get the content of a file that doesn’t exists as first command.

$ cat nofile.txt; echo "Second string"

Well, the output of this double command is an error message from cat (which mercilessly sends us

to the naughty step), followed by the output of the echo command. So, the semicolon is executing

both commands whatever the result of them.

It is however often useful to chain commands in a different way, where a failing command interrupts

the execution. For example you might want to find all files with a certain name and create a log file

with some statistics, but you don’t want to run this last step if there are no files. For the time being

let’s see what the operator && does to the previous two commands

$ cat nofile.txt && echo "Second string"

It looks like this is exactly what we were looking for. We get the error message from cat (and the

naughty step again, sorry), but no output from echo. Bash interrupted the execution because one

command failed. Put this is your belt, it will come in handy sooner or later.

There is a third ancient glyph that made it through the fall of the ancient Egyptian kingdom and

landed in the Unix system, and it is one of the most important operators that you have to learn. So,

grab some strong coffee, you need to be awake.